package com.wude.guild.holder;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.akexorcist.roundcornerprogressbar.RoundCornerProgressBar;
import com.mc.developmentkit.utils.MCUtils;
import com.mc.developmentkit.utils.ToastUtil;
import com.wude.bean.AppInfo;
import com.wude.guild.DownloadActivity;
import com.wude.guild.R;
import com.wude.guild.manager.DownloadManager;
import com.wude.guild.views.RoundAngleImageView;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.tools.DbUtils;
import com.wude.tools.Utils;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * 首页游戏item
 * Created by LeBron on 2017/2/7.
 */

@SuppressLint("HandlerLeak")
public class HomeGameHolder extends BaseHolder<AppInfo> {

    @BindView(R.id.home_game_icon)
    RoundAngleImageView homeGameIcon;
    @BindView(R.id.home_game_jicon)
    ImageView homeGameJIcon;
    @BindView(R.id.home_game_name)
    TextView homeGameName;
    @BindView(R.id.home_game_ratingBar)
    RatingBar homeGameRatingBar;
    @BindView(R.id.down_num)
    TextView downNum;
    @BindView(R.id.home_game_size)
    TextView homeGameSize;
    @BindView(R.id.jianjie)
    TextView jianjie;
    @BindView(R.id.spend)
    TextView spend;
    @BindView(R.id.size)
    TextView size;
    @BindView(R.id.progressbar)
    RoundCornerProgressBar progressbar;
    @BindView(R.id.delete)
    ImageView delete;
    @BindView(R.id.home_game_fanli)
    TextView homeGameFanli;
    @BindView(R.id.home_game_download)
    TextView homeGameDownload;
    @BindView(R.id.game_size)
    TextView gameSize;
    @BindView(R.id.down_layout)
    RelativeLayout downLayout;
    @BindView(R.id.ll_home_game_download)
    LinearLayout downGame;
    @BindView(R.id.iv_downIcon)
    ImageView downIcom;
    private DbManager db;
    private AppInfo down;
    private int id;
    private Activity activity;
    private boolean an = true;
    private boolean del = true;
    private boolean suo = true;         //点击下载时为false   获得下载衔接是为true  防止重复点击
    private Context context;

    @Override
    protected void refreshView(final AppInfo gameInfo, int position, final Activity activity) {
        String s = activity.getClass().toString();
        this.activity = activity;
        if (s.equals(HttpCom.getDeownloadCenter())) {
//            delete.setVisibility(View.VISIBLE);
            HashMap<String, String> map = new HashMap<>();
            map.put("game_id", gameInfo.id + "");
            HttpCom.POST(vhandler, HttpCom.getGameDetUrl(), map, false);
        } else {
            delete.setVisibility(View.GONE);
        }
        setdata(gameInfo);
        if (db == null) {
            db = DbUtils.getDB();
        }
        down = down(gameInfo);
        id = gameInfo.id;
        Status(down);
    }


    public void setdata(AppInfo gameInfo) {
        MCUtils.fillImage(homeGameIcon, gameInfo.iconurl);
        if (TextUtils.isEmpty(gameInfo.cover_banner))
            homeGameJIcon.setImageResource(R.mipmap.loading);
        else
            MCUtils.fillImage(homeGameJIcon, gameInfo.cover_banner);

        String jieQu = Utils.getJieQu(gameInfo.name);
        homeGameName.setText(jieQu);
        gameSize.setText(gameInfo.size);
        downNum.setText("下载人数：" + gameInfo.DownNum);
//        if (gameInfo.fanli == null || gameInfo.fanli.equals("0.00")) {
//            homeGameFanli.setVisibility(View.INVISIBLE);
//        } else {
//            homeGameFanli.setVisibility(View.VISIBLE);
//            homeGameFanli.setText("返利" + gameInfo.fanli + "%");
//        }
        homeGameRatingBar.setRating(gameInfo.rating);
        downGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                xiazai();
            }
        });
        jianjie.setText(gameInfo.features);
    }

    @Override
    protected View initView() {
        View inflate = LinearLayout.inflate(x.app(), R.layout.home_game_item, null);
        context = inflate.getContext();
        ButterKnife.bind(this, inflate);
        inflate.setTag(this);
        return inflate;
    }

    public AppInfo down(AppInfo app) {
        try {
            AppInfo byId = db.findById(AppInfo.class, app.id);
            if (byId == null) {
                return app;
            } else {
                return byId;
            }
        } catch (DbException e) {
            e.printStackTrace();
            return null;
        }
    }


    public void Status(AppInfo app) {
        switch (app.btnStatus) {
            case DownloadManager.DOWNLOAD_WAITING:
                homeGameDownload.setText("等待");
                homeGameDownload.setBackgroundResource(R.drawable.btn_queren_hui);
//                downIcom.setImageResource(R.mipmap.home_wait);
                jianjie.setVisibility(View.GONE);
                downLayout.setVisibility(View.VISIBLE);
                progressbar.setProgress(0);
                spend.setText("0kb/s");
                size.setText("0M/0M");
                break;
            case DownloadManager.DOWNLOAD_NOT:
                del = true;
                an = true;
                homeGameDownload.setText("下载");
                homeGameDownload.setBackgroundResource(R.drawable.btn_queren);
//                downIcom.setImageResource(R.mipmap.home_down);
                downLayout.setVisibility(View.GONE);
//                jianjie.setVisibility(View.VISIBLE);
                break;
            case DownloadManager.DOWNLOAD_LOADING:
                int progress = (int) (app.progress * 100f / app.zsize + 0.5f);
                progressbar.setProgress(progress);
                homeGameDownload.setText("暂停");
//                downIcom.setImageResource(R.mipmap.home_pause);
                homeGameDownload.setBackgroundResource(R.drawable.btn_queren_hui);
                jianjie.setVisibility(View.GONE);
                downLayout.setVisibility(View.VISIBLE);
                String size = Utils.getSize(app.progress, app.zsize);
                spend.setText(app.spent);
                this.size.setText(size);
                break;
            case DownloadManager.DOWNLOAD_SUCCESS:
                homeGameDownload.setText("安装");
                homeGameDownload.setBackgroundResource(R.drawable.btn_queren);
                downIcom.setVisibility(View.GONE);
                downLayout.setVisibility(View.GONE);
//                jianjie.setVisibility(View.VISIBLE);
                if (an) {
                    an = false;
                    an();
                }
                break;
            case DownloadManager.DOWNLOAD_FAILED:
                homeGameDownload.setText("重试");
                homeGameDownload.setBackgroundResource(R.drawable.btn_queren_juhuang);
                downLayout.setVisibility(View.GONE);
//                downIcom.setImageResource(R.mipmap.home_retry);
//                jianjie.setVisibility(View.VISIBLE);
                break;
            case DownloadManager.DOWNLOAD_INSTALL:
                homeGameDownload.setText("打开");
                homeGameDownload.setTextColor(context.getResources().getColor(R.color.white));
//                downIcom.setVisibility(View.GONE);
                homeGameDownload.setBackgroundResource(R.drawable.btn_queren);
                downLayout.setVisibility(View.GONE);
//                jianjie.setVisibility(View.VISIBLE);
                if (del) {
                    del = false;
                    an();
                }
                break;
            case DownloadManager.DOWNLOAD_PAUSE:
                homeGameDownload.setText("继续");
                homeGameDownload.setBackgroundResource(R.drawable.btn_queren_hui);
//                downIcom.setImageResource(R.mipmap.home_goon);
                downLayout.setVisibility(View.GONE);
//                jianjie.setVisibility(View.VISIBLE);
                break;
        }
    }

    public void xiazai() {
        AppInfo down1 = down(this.down);
        switch (down1.btnStatus) {
            case DownloadManager.DOWNLOAD_NOT:
                if (suo) {
                    suo = false;
                    Utils.getDownLoadUrl(handler, down1.id);
                    homeGameDownload.setText("等待");
                    homeGameDownload.setBackgroundResource(R.drawable.btn_queren_hui);
                    jianjie.setVisibility(View.GONE);
                    downLayout.setVisibility(View.VISIBLE);
                    progressbar.setProgress(0);
                    spend.setText("0kb/s");
                    size.setText("0M/0M");
                }
                break;
            case DownloadManager.DOWNLOAD_WAITING:
                PuseDownLoad(down1);
                break;
            case DownloadManager.DOWNLOAD_LOADING:
                PuseDownLoad(down1);
                break;
            case DownloadManager.DOWNLOAD_SUCCESS:
                InStall(down1);
                break;
            case DownloadManager.DOWNLOAD_FAILED:
                if (suo) {
                    suo = false;
                    Utils.getDownLoadUrl(handler, down1.id);
                }
                break;
            case DownloadManager.DOWNLOAD_INSTALL:
                Open(down1);
                break;
            case DownloadManager.DOWNLOAD_PAUSE:
                StartDownLoad(down1);
                break;
        }
    }

    public void Refresh(AppInfo appInfo) {
        if (appInfo.id == id) {
            Status(appInfo);
        }
    }

    public void StartDownLoad(AppInfo app) {
        DownloadManager.getInstance().down(app);
    }

    public void PuseDownLoad(AppInfo app) {
        DownloadManager.getInstance().pause(app);
    }

    public void InStall(AppInfo app) {
        DownloadManager.getInstance().install(app);
    }

    public void Open(AppInfo app) {
        DownloadManager.getInstance().open(app);
    }

    /**
     * 下载完成后是否删除安装包并且判断是否真的安装过了
     */
    public void an() {
        if (down != null) {
            AppInfo down1 = down(this.down);
            DownloadManager.getInstance().isInstall(down1);
        }
    }

    @OnClick({R.id.delete})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.delete:
                delete();
                break;
        }
    }

    /**
     * 删除下载
     */
    public void delete() {
        DownloadManager.getInstance().delete(down);
        DownloadActivity activity = (DownloadActivity) this.activity;
        activity.getDownLoadList();
    }

    /**
     * 获得下载链接
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    String url = HttpUtils.DNSdownUrl(msg.obj.toString());
                    if (url != null && !url.equals("")) {
                        down = down(down);
                        down.url = url;
                        StartDownLoad(down);
                        suo = true;
                    }
                    break;
                case 2:
                    if (msg.obj.toString().equals("java.net.SocketTimeoutException")) {
                        Utils.getDownLoadUrl(handler, down.id);
                    } else {
                        ToastUtil.showToast("网络异常");
                    }
                    break;
            }
        }
    };

    /**
     * 游戏详情
     */
    Handler vhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    AppInfo appInfo = HttpUtils.DNSGameDel(msg.obj.toString());
                    if (appInfo != null) {
                        setdata(appInfo);
                    } else {
                        delete();
                    }
                    break;
                case 2:
                    ToastUtil.showToast("网络异常");
                    break;
            }
        }
    };
}
